#include <pthread.h>
#include "sys.h"


int sys_popen(char *p_arg, unsigned short argbuf_len) {
	FILE * fp; 
	int res; 
	//printf(" %s\n",p_arg);
	if ((fp = popen(p_arg, "r") ) == NULL) { 
		printf("popen err: %s", p_arg);
		return -1; 
	} 
	else {
		//while( fgets(p_arg, argbuf_len, fp)) { printf(" %s", p_arg); }
		if ( (res = pclose(fp))!= 0) { 
			printf("popen close err: %s %d!\n", p_arg, res); 
			return -2;
		} 
	}
	return 0;
}


static unsigned int console_lv=1;
void console_lv_set(unsigned char ch)
{
	if(ch >= 32)
		return;
	console_lv |= 0x1<<ch;
}

void console_lv_clear(unsigned char ch)
{
	if(ch >= 32)
		return;
	console_lv &= ~(0x1<<ch);
}

unsigned int console_lv_get(unsigned char ch)
{
	if(ch >= 32)
		return 0;
	return console_lv&(0x1<<ch);
}


#if 0
void argdbg(unsigned int arg, char *str)
{
	mydbg("%s=%d\r\n", str, arg);
}

void argdbgx(unsigned int arg, char *str)
{
	mydbg("%s=0x%x\r\n", str, arg);
}
#endif


void myarray(unsigned char *data, unsigned int len) {
    unsigned int i;
    for(i = 0; i < len; i++) {
        printf("%02x ", data[i]); 
        if(i > 0 && i%64 == 0) {
            printf("\r\n");
        }
    }
    printf("\r\n");
}



#define SYS_LOG_ENABLE
#ifdef SYS_LOG_ENABLE

#define LOG_STR_END "\\r\\n"	//web str end flag
#define LOG_MAX_LEN 4096
#define MAX_STR_LEN 127
static char sys_logbuf[LOG_MAX_LEN+4]={0};
static unsigned short sys_log_len=0;


static pthread_mutex_t slog_mutex = PTHREAD_MUTEX_INITIALIZER;
#define LOG_GET_LOCK()  pthread_mutex_unlock(&slog_mutex)
#define LOG_LOCK()      pthread_mutex_lock(&slog_mutex)
static void write_log(const char *str)
{
	LOG_GET_LOCK();
	unsigned short rlen= LOG_MAX_LEN- sys_log_len;
	if(rlen > MAX_STR_LEN +1)
		sys_log_len+= snprintf(&sys_logbuf[sys_log_len], rlen, "%s%s", str, LOG_STR_END);
	else{	
		char* copy_line; 
		sys_logbuf[LOG_MAX_LEN]=0;
		/*移动3/4的旧日志到头部，以\r\n作为一条日志的标识*/
		copy_line= strstr(&sys_logbuf[sys_log_len/4], LOG_STR_END);
		if(copy_line!= NULL){
			copy_line+= strlen(LOG_STR_END);
			sys_log_len= &sys_logbuf[sys_log_len]- copy_line;
			memcpy(sys_logbuf, copy_line, sys_log_len);
		}
		else{
			sys_log_len=0;/*移动失败，清空*/
		}
		rlen= LOG_MAX_LEN- sys_log_len;
		sys_log_len+= snprintf(&sys_logbuf[sys_log_len], rlen, "%s%s", str, LOG_STR_END);
	}
	LOG_LOCK();
}


char* read_log(void)
{
	return sys_logbuf;
}


#if 1
void sys_log(char* fmt,...)
{  
	#include <stdarg.h>
	#include "app_delay.h"
	unsigned int t;
	int i=0;
	char log_temp[MAX_STR_LEN+1]; 
	char* pbuf = log_temp;
	va_list ap;
	va_start(ap,fmt);
	
	t= getNowTime()/1000;
	i= sprintf((char*)pbuf,"%02d:%02d:%02d  ",(t/(60*60))%60, (t/60)%60, t%60);
	
	i+= vsnprintf((char*)&pbuf[i], MAX_STR_LEN-i, fmt,ap);
	va_end(ap);
	write_log(pbuf);
}

#else
#include "nstar_sntp.h"
#include <stdarg.h>

void sys_log(char* fmt,...)
{  
	NATAR_OS_TIME os_t;
	int i=0;
	char log_temp[MAX_STR_LEN+1]; 
	char* pbuf = log_temp;
	va_list ap;
	va_start(ap,fmt);
	read_time(&os_t);	
	
	i= sprintf((char*)pbuf,"%04d-%02d-%02d %02d:%02d:%02d ", os_t.year, os_t.mon, os_t.day,
		os_t.hour, os_t.min, os_t.sec);
	
	i+= vsnprintf((char*)&pbuf[i], MAX_STR_LEN-i, fmt,ap);
	va_end(ap);
	write_log(pbuf);
}


#endif

#endif

#include <ucontext.h>
#include <execinfo.h>
#include <signal.h>

static void _signal_handler(int sig,siginfo_t *info,void *ctx)
{

    ucontext_t *context=(ucontext_t*)ctx;
    void *p_buf[256];
    char**p_strs;
    int i,nptrs;
    printf("signal=%d memory location=%p\n",sig,info->si_addr);
    nptrs = backtrace(p_buf,256);
    p_strs = backtrace_symbols(p_buf,nptrs);
    if(p_strs == NULL){
        perror("symbols err");
        exit(-1);
    }
    for(i=0;i<nptrs;i++){
        printf(" [%02d] %s\n",i,p_strs[i]);
    }
    free(p_strs);
}

void set_coredump(void) 
{
	struct sigaction action;
	sigemptyset(&action.sa_mask);
	action.sa_sigaction = _signal_handler;
	action.sa_flags = SA_SIGINFO;
	sigaction(SIGSEGV,&action,NULL);
}






